﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ServerApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            IPHostEntry localMachineInfo = Dns.GetHostEntry(Dns.GetHostName());
            for (int i = 0; i < localMachineInfo.AddressList.Length; i++)
            {
                if (localMachineInfo.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    IPCombo.Items.Add(localMachineInfo.AddressList[i].ToString());
            }
        }

        private void StartBtn_Click(object sender, EventArgs e)
        {
            if (IPCombo.SelectedItem.ToString() == string.Empty)
                return;
            int port;
            try
            {
                port = int.Parse(PortTBox.Text);
            }
            catch
            {
                return;
            }
            Server.Start(IPAddress.Parse(IPCombo.SelectedItem.ToString()), port);

            StartBtn.Visible = false;
        }

        private void RefreshBtn_Click(object sender, EventArgs e)
        {
            RefreshGrid();
        }

        private void ClearLogBtn_Click(object sender, EventArgs e)
        {
            System.IO.File.Delete(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt"));
            RefreshGrid();
        }

        private void RefreshGrid()
        {
            LogGrid.Rows.Clear();
            System.IO.StreamReader file = null;
            List<string> logLines = new List<string>();
            try
            {
                file = new System.IO.StreamReader(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log.txt"));
                string line;
                while ((line = file.ReadLine()) != null)
                    logLines.Add(line);
            }
            catch
            {
                return;
            }
            finally
            {
                if (file != null)
                    file.Close();
            }
            for (int i = 0; i < logLines.Count; i++)
            {
                LogGrid.Rows.Add(logLines[i]);
            }
        }
        
    }
}
